import {View, ScrollView, Text} from "@tarojs/components";
import Utils from "@/utils/common";
import {Button, Cell, Divider, Empty, Search, Image} from "@antmjs/vantui";

import {useCallback, useRef, useState} from "react";
import {orderCancelApi, orderInfoApi} from "@/common/apis/home_datasource";
import {OrderItem} from "@/common/apis/model";
import {getOrderStatusStyle, OrderStatus} from "@/common/enums";
import RouthPath from "@/common/RouthPath";
import ShowUtils from "@/utils/show_utils";
import LocalData from "@/common/local_data";
import NumberUtils from "@/utils/number_utils";

definePageConfig({
  navigationBarTitleText: '查询订单'
})

export default function SearchOrderList() {
  const [orderItem, setOrderItem] = useState<OrderItem[]>()

  const inputKey = useRef('');
  const getOrderList = useCallback(() => {
    orderInfoApi(inputKey.current).then((res) => {
      if (res) {
        setOrderItem([res])
      }
    })
  }, []);

  const handleButtons = useCallback((e, item, type) => {
    e.stopPropagation(); // 阻止事件冒泡到父级的 onClick
    if (type === -1) {
      Utils.modal("提示", "确定要取消吗？", true, (ok) => {
        if (ok) {
          orderCancelApi(item.id).then((r) => {
            if (r) {
              Utils.showOkToast("取消成功")
              getOrderList()
            }
          })
        }
      })
    }
  }, [getOrderList]);

  const renderActionButtons = useCallback((item) => {
    let buttons = null;
    let cancelButton = (
      <Button style={{marginRight: '10px'}} size='normal' type='info' hairline plain onClick={(e) => {
        handleButtons(e, item, -1);
      }}
      >
        取消
      </Button>
    )
    if (item.status < OrderStatus.FINISHED) {
      buttons = (
        <View>
          {cancelButton}
        </View>
      )
    }
    if (buttons) {
      return (
        <View>
          <View style={{
            display: 'flex',
            flexDirection: 'row',
            margin: '10px',
            boxSizing: 'border-box',
            justifyContent: 'flex-end',
          }}
          >
            {buttons}
          </View>
          <Divider style={{marginTop: '0px'}}/> {/* 如果按钮存在，Divider 可以在按钮之后 */}
        </View>
      );
    }
    return null; // 如果没有匹配的状态，则不渲染按钮区域
  }, [handleButtons]);

  const searchAction = useCallback((e) => {
    if (!Utils.isNotBlank(e.detail)) {
      Utils.showErrorToast('请输入订单号')
      return;
    }
    if (e.detail === inputKey.current) {
      return;
    }
    inputKey.current = e.detail;
    getOrderList()

  }, [getOrderList]);

  const showTimeOrNum = useCallback((item:OrderItem) => {
    const type = item.machineType
    if (type === LocalData.notTimeId) {
      return `样品数量：${NumberUtils.stringToNumber(item.bookTotalTime)}`
    }else{
      return `预约时间：${ShowUtils.getShowTime(item.bookAllTimes)}`
    }
  }, []);


  const renderItem = useCallback((item) => {
    const orderStatusInfo = getOrderStatusStyle(item.status)
    return <View key={item.id} onClick={() => {
      const url = Utils.getUrlWithObject(RouthPath.orderDetail, {
        id: item.id
      })
      Utils.navigateTo({
        url: url
      })
      //传入url 和 doAction(data)
    }}
    >
      <Cell renderIcon={<Text style={{fontSize: '14px'}}>订单号：{item.id}</Text>}
            renderTitle={<Text
              style={{
                color: orderStatusInfo.color,
                textAlign: 'right',
                fontSize: '14px',
                width: '100%',
                display: 'inline-block',
              }}
            >{orderStatusInfo.text}</Text>}

      />
      <View style={{display: 'flex', flexDirection: 'row', padding: '10px 20px', boxSizing: 'border-box'}}>
        <View>
          <Image src={item.projectImage} style={{width: '150px', height: '150px'}} mode='aspectFill'/>
        </View>
        <View
          style={{marginLeft: '10px', display: 'flex', flexDirection: 'column', flex: 1, height: '150px'}}
        >
          <Text>机器：{item.machineName}</Text>
          <View>
            <Text>项目：{item.projectName}</Text>
            {/*{item.note ? <Text style={{color: 'gray',fontSize: '12px'}}>{`(${item.note})`}</Text> : null}*/}
          </View>
          <Text>{showTimeOrNum(item)}</Text>
          <View style={{flex: 1, display: 'flex', justifyContent: 'flex-end'}}>
            <Text style={{
              fontSize: '16px',
              color: 'red',
              textAlign: 'right',
              marginTop: '10px',
              alignSelf: 'flex-end'
            }}
            >{ShowUtils.getDefaultPrice(item.actualAmount)}</Text>
            <Text style={{
              fontSize: '16px',
              color: 'gray',
              textAlign: 'right',
              marginTop: '10px',
              alignSelf: 'flex-end',
              textDecoration: 'line-through',
            }}
            >{`(${ShowUtils.getDefaultPrice(item.amount)})`}</Text>
          </View>
        </View>
      </View>
      <Divider style={{margin: '0px 20px'}}/>
      {
        renderActionButtons(item)
      }
    </View>
  }, []);

  return (
    <View
      style={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        width: '100%',
        height: '100VH',
        boxSizing: 'border-box',
        padding: '10px',
      }}
    >
      <View>
        <Search
          placeholder='请输入搜索订单号'
          onSearch={searchAction}
        />
      </View>
      <ScrollView scrollY style={{height: '100%'}}>
        {
          orderItem ? orderItem.map((item, index) => (
            renderItem(item))) : <Empty description='暂无数据'/>
        }
      </ScrollView>
    </View>
  )

}


